package com.mvc.base.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.mvc.base.model.UserCompany;
import com.mvc.framework.service.BaseService;
import com.mvc.framework.util.FrameworkContextUtils;

@Service
public class UserCompanyManager extends BaseService<UserCompany, Integer> {

	public List<UserCompany> getUserCompanyByUserId(Integer userId) {
		UserCompany userCompanyPrivilege = new UserCompany();
		userCompanyPrivilege.setUserId(userId);
		return getHibernateTemplate().findByExample(userCompanyPrivilege);
	}

	public void saveUserCompanyPrivileges(List<UserCompany> companyPrivileges, Integer userId) {
		deleteByWhere("userId=" + userId);
		for (UserCompany companyPrivilege : companyPrivileges) {
			save(companyPrivilege);
		}
	}

	public String getCompanyIdsByUserId(Integer userId) {
		if (userId == FrameworkContextUtils.SYSTEM_ID) {
			return null;
		} else {
			List<UserCompany> companyPrivileges = getUserCompanyByUserId(userId);
			if (companyPrivileges.size() > 0) {
				StringBuilder companyIds = new StringBuilder();
				for (UserCompany privilege : companyPrivileges) {
					companyIds.append(privilege.getCompanyId()).append(",");
				}
				return companyIds.substring(0, companyIds.length() - 1);
			}
			return "";
		}
	}
}
